package cn.demomaster.quickui.util.screen;

import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

/**
 * 监听录屏
 */
public class ScreenRecordObserver extends ContentObserver {
    public static final String SCREEN_RECORD_STATE_PATH = "/sys/class/graphics/fb0/screen_state";

    private OnScreenRecordStateChangedListener listener;

    public ScreenRecordObserver(Handler handler) {
        super(handler);
    }

    public void setOnScreenRecordStateChangedListener(OnScreenRecordStateChangedListener listener) {
        this.listener = listener;
    }

    @Override
    public void onChange(boolean selfChange, Uri uri) {
        if (listener != null) {
            boolean isRecording = isScreenRecording();
            listener.onScreenRecordStateChanged(isRecording);
        }
    }

    private boolean isScreenRecording() {
        try {
            FileInputStream fis = new FileInputStream(SCREEN_RECORD_STATE_PATH);
            BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(fis));
            String state = bufferedReader.readLine();
            bufferedReader.close();
            return !"0".equals(state);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return false;
    }


    public interface OnScreenRecordStateChangedListener {
        void onScreenRecordStateChanged(boolean isRecording);
    }
}
